// TMDB页面JavaScript功能实现

// 等待DOM加载完成
document.addEventListener('DOMContentLoaded', function() {
    // 初始化页面
    initPage();
});

// 页面初始化函数
function initPage() {
    // 绑定搜索按钮事件
    document.getElementById('search-button').addEventListener('click', performSearch);
    document.getElementById('tmdb-search-input').addEventListener('keypress', function(e) {
        if (e.key === 'Enter') {
            performSearch();
        }
    });
    
    // 绑定刷新按钮事件
    document.getElementById('refresh-movies').addEventListener('click', loadRecentMovies);
    document.getElementById('refresh-tv').addEventListener('click', loadRecentTV);
    
    // 绑定滚动按钮事件
    setupScrollButtons('movies');
    setupScrollButtons('tv');
    
    // 加载初始数据
    loadRecentMovies();
    loadRecentTV();
}

// 设置自动滚动功能
function setupScrollButtons(type) {
    const leftButton = document.getElementById(`scroll-left-${type}`);
    const rightButton = document.getElementById(`scroll-right-${type}`);
    const scrollContainer = document.getElementById(`${type}-scroll-container`);
    const listElement = document.getElementById(`${type}-list`);
    
    // 隐藏滚动按钮
    leftButton.style.display = 'none';
    rightButton.style.display = 'none';
    
    let scrollInterval;
    let scrollAmount = 1; // 每次滚动的像素数
    let scrollSpeed = 20; // 滚动间隔(毫秒)
    
    // 启动自动滚动
    function startAutoScroll() {
        if (scrollInterval) return;
        
        scrollInterval = setInterval(() => {
            const scrollWidth = scrollContainer.scrollWidth;
            const clientWidth = scrollContainer.clientWidth;
            
            // 如果已经滚动到最右侧，回到开始位置
            if (scrollContainer.scrollLeft >= scrollWidth - clientWidth - 10) {
                scrollContainer.scrollTo({ left: 0, behavior: 'smooth' });
                clearInterval(scrollInterval);
                scrollInterval = null;
                // 延迟后重新开始滚动
                setTimeout(startAutoScroll, 2000);
            } else {
                scrollContainer.scrollBy({ left: scrollAmount, behavior: 'auto' });
            }
        }, scrollSpeed);
    }
    
    // 停止自动滚动
    function stopAutoScroll() {
        if (scrollInterval) {
            clearInterval(scrollInterval);
            scrollInterval = null;
        }
    }
    
    // 鼠标悬停时停止滚动，离开时继续滚动
    scrollContainer.addEventListener('mouseenter', stopAutoScroll);
    scrollContainer.addEventListener('mouseleave', startAutoScroll);
    
    // 初始启动自动滚动
    startAutoScroll();
}

// 执行搜索
function performSearch() {
    const searchInput = document.getElementById('tmdb-search-input');
    const searchType = document.getElementById('search-type').value;
    const keyword = searchInput.value.trim();
    
    if (!keyword) {
        alert('请输入搜索关键词');
        return;
    }
    
    // 显示加载状态
    const resultsContainer = document.getElementById('results-container');
    resultsContainer.innerHTML = '<div class="loading-spinner-container flex items-center justify-center h-64 w-full"><div class="loading-spinner"></div></div>';
    
    // 显示搜索结果区域
    document.getElementById('search-results').classList.remove('hidden');
    
    // 发送搜索请求
    fetch(`/api/tmdb/search?q=${encodeURIComponent(keyword)}&type=${searchType}`)
        .then(response => response.json())
        .then(data => {
            if (data.success && data.data && data.data.length > 0) {
                displaySearchResults(data.data, searchType);
            } else {
                resultsContainer.innerHTML = '<div class="text-center text-gray-500 py-10">未找到相关内容</div>';
            }
        })
        .catch(error => {
            console.error('搜索失败:', error);
            resultsContainer.innerHTML = '<div class="text-center text-red-500 py-10">搜索失败，请稍后重试</div>';
        });
}

// 显示搜索结果
function displaySearchResults(results, type) {
    const resultsContainer = document.getElementById('results-container');
    resultsContainer.innerHTML = '';
    
    results.forEach(item => {
        const card = createMediaCard(item, type);
        resultsContainer.appendChild(card);
    });
}

// 加载24小时内最新电影
function loadRecentMovies() {
    const moviesList = document.getElementById('movies-list');
    moviesList.innerHTML = '<div class="loading-spinner-container flex items-center justify-center h-64 w-full"><div class="loading-spinner"></div></div>';
    
    fetch('/api/tmdb/recent-movies')
        .then(response => response.json())
        .then(data => {
            if (data.success && data.data && data.data.length > 0) {
                displayMediaList(data.data, 'movies', 'movie');
            } else {
                moviesList.innerHTML = '<div class="text-center text-gray-500 py-10">暂无最新电影数据</div>';
            }
        })
        .catch(error => {
            console.error('加载最新电影失败:', error);
            moviesList.innerHTML = '<div class="text-center text-red-500 py-10">加载失败，请稍后重试</div>';
        });
}

// 加载24小时内最新电视节目
function loadRecentTV() {
    const tvList = document.getElementById('tv-list');
    tvList.innerHTML = '<div class="loading-spinner-container flex items-center justify-center h-64 w-full"><div class="loading-spinner"></div></div>';
    
    fetch('/api/tmdb/recent-tv')
        .then(response => response.json())
        .then(data => {
            if (data.success && data.data && data.data.length > 0) {
                displayMediaList(data.data, 'tv', 'tv');
            } else {
                tvList.innerHTML = '<div class="text-center text-gray-500 py-10">暂无最新电视节目数据</div>';
            }
        })
        .catch(error => {
            console.error('加载最新电视节目失败:', error);
            tvList.innerHTML = '<div class="text-center text-red-500 py-10">加载失败，请稍后重试</div>';
        });
}

// 打开媒体详情弹窗
function openMediaDetailModal(mediaId, mediaType) {
    const modal = document.getElementById('media-detail-modal');
    const modalLoading = document.getElementById('modal-loading');
    const modalContent = document.getElementById('modal-content');
    
    // 显示弹窗和加载状态
    modal.classList.remove('hidden');
    modalLoading.classList.remove('hidden');
    modalContent.classList.add('hidden');
    
    // 发送请求获取媒体详情
    fetch(`/api/tmdb/detail?id=${mediaId}&type=${mediaType}`)
        .then(response => response.json())
        .then(data => {
            modalLoading.classList.add('hidden');
            
            if (data.success && data.data) {
                renderMediaDetail(data.data);
                modalContent.classList.remove('hidden');
            } else {
                modalContent.innerHTML = '<div class="text-center text-red-500 py-10">获取媒体详情失败</div>';
                modalContent.classList.remove('hidden');
            }
        })
        .catch(error => {
            console.error('获取媒体详情失败:', error);
            modalLoading.classList.add('hidden');
            modalContent.innerHTML = '<div class="text-center text-red-500 py-10">获取媒体详情失败</div>';
            modalContent.classList.remove('hidden');
        });
}

// 渲染媒体详情
function renderMediaDetail(media) {
    const modalContent = document.getElementById('modal-content');
    const modalTitle = document.getElementById('modal-title');
    
    // 设置标题
    modalTitle.textContent = media.type === 'movie' ? media.title : media.name;
    
    // 构建详情HTML
    let html = `
        <div class="grid grid-cols-1 md:grid-cols-3 gap-6">
            <!-- 海报区域 -->
            <div class="md:col-span-1">
                <div class="rounded-lg overflow-hidden shadow-lg">
                    <img src="${media.poster_url || '/static/images/placeholder.png'}" alt="${media.type === 'movie' ? media.title : media.name}" class="w-full h-auto">
                </div>
                <div class="mt-4 space-y-2">
                    <button id="download-poster-btn" class="w-full py-2 px-4 bg-primary text-white rounded-lg hover:bg-primary/90 transition-colors flex items-center justify-center">
                        <i class="fa fa-download mr-2"></i> 下载海报
                    </button>
                    <button id="generate-nfo-btn" class="w-full py-2 px-4 bg-secondary text-white rounded-lg hover:bg-secondary/90 transition-colors flex items-center justify-center">
                        <i class="fa fa-file-code-o mr-2"></i> 生成NFO文件
                    </button>
                </div>
            </div>
            
            <!-- 信息区域 -->
            <div class="md:col-span-2">
                <h3 class="text-lg font-semibold mb-4">基本信息</h3>
                <div class="space-y-3">
                    <p><strong>标题:</strong> ${media.type === 'movie' ? media.title : media.name}</p>
                    ${media.type === 'movie' && media.original_title ? `<p><strong>原始标题:</strong> ${media.original_title}</p>` : ''}
                    ${media.type === 'tv' && media.original_name ? `<p><strong>原始名称:</strong> ${media.original_name}</p>` : ''}
                    ${media.type === 'movie' && media.release_date ? `<p><strong>上映日期:</strong> ${formatDate(media.release_date)}</p>` : ''}
                    ${media.type === 'tv' && media.first_air_date ? `<p><strong>首播日期:</strong> ${formatDate(media.first_air_date)}</p>` : ''}
                    ${media.vote_average ? `<p><strong>评分:</strong> ${media.vote_average}/10 (${media.vote_count} 评价)</p>` : ''}
                    ${media.genres && media.genres.length ? `<p><strong>类型:</strong> ${media.genres.join(', ')}</p>` : ''}
                    ${media.countries && media.countries.length ? `<p><strong>国家/地区:</strong> ${media.countries.join(', ')}</p>` : ''}
                    ${media.runtime ? `<p><strong>时长:</strong> ${media.runtime} 分钟</p>` : ''}
                    ${media.type === 'tv' && media.number_of_seasons ? `<p><strong>季数:</strong> ${media.number_of_seasons}</p>` : ''}
                    ${media.type === 'tv' && media.number_of_episodes ? `<p><strong>集数:</strong> ${media.number_of_episodes}</p>` : ''}
                    ${media.certification ? `<p><strong>分级:</strong> ${media.certification}</p>` : ''}
                    ${media.imdb_id ? `<p><strong>IMDb ID:</strong> ${media.imdb_id}</p>` : ''}
                    ${media.tmdb_id ? `<p><strong>TMDB ID:</strong> ${media.tmdb_id}</p>` : ''}
                </div>
                
                <h3 class="text-lg font-semibold mt-6 mb-4">简介</h3>
                <p class="text-gray-700 whitespace-pre-line">${media.overview || '暂无简介'}</p>
                
                ${media.directors && media.directors.length ? `
                <h3 class="text-lg font-semibold mt-6 mb-4">导演</h3>
                <p>${media.directors.join(', ')}</p>
                ` : ''}
                
                ${media.writers && media.writers.length ? `
                <h3 class="text-lg font-semibold mt-4 mb-4">编剧</h3>
                <p>${media.writers.join(', ')}</p>
                ` : ''}
                
                ${media.creators && media.creators.length ? `
                <h3 class="text-lg font-semibold mt-4 mb-4">创作者</h3>
                <p>${media.creators.join(', ')}</p>
                ` : ''}
                
                ${media.actors && media.actors.length ? `
                <h3 class="text-lg font-semibold mt-6 mb-4">演员</h3>
                <div class="flex flex-wrap gap-2">
                    ${media.actors.map(actor => `<span class="bg-gray-100 px-3 py-1 rounded-full text-sm">${actor.name}</span>`).join('')}
                </div>
                ` : ''}
            </div>
        </div>
        
        <!-- NFO生成结果区域 -->
        <div id="nfo-result" class="mt-6 hidden">
            <div class="bg-green-50 border border-green-200 rounded-lg p-4">
                <h4 class="text-green-700 font-medium flex items-center">
                    <i class="fa fa-check-circle mr-2"></i> NFO文件生成成功
                </h4>
                <p class="text-green-600 mt-2" id="nfo-file-path"></p>
                <button id="download-nfo-btn" class="mt-3 py-1 px-4 bg-green-600 text-white rounded hover:bg-green-700 transition-colors">
                    <i class="fa fa-download mr-1"></i> 下载NFO文件
                </button>
            </div>
        </div>
    `;
    
    modalContent.innerHTML = html;
    
    // 存储当前媒体信息到按钮上，以便后续操作
    document.getElementById('download-poster-btn').dataset.media = JSON.stringify(media);
    document.getElementById('generate-nfo-btn').dataset.media = JSON.stringify(media);
    
    // 绑定下载海报按钮事件
    document.getElementById('download-poster-btn').addEventListener('click', downloadPoster);
    
    // 绑定生成NFO按钮事件
    document.getElementById('generate-nfo-btn').addEventListener('click', generateNFOFile);
}

// 显示媒体列表
function displayMediaList(items, listType, mediaType) {
    const listElement = document.getElementById(`${listType}-list`);
    listElement.innerHTML = '';
    
    items.forEach(item => {
        const card = createMediaCard(item, mediaType);
        listElement.appendChild(card);
    });
}

// 创建媒体卡片
function createMediaCard(item, type) {
    const card = document.createElement('div');
    card.className = 'tmdb-card cursor-pointer hover:shadow-lg transition-shadow';
    
    // 获取标题和日期
    const title = type === 'movie' ? item.title : item.name;
    const releaseDate = type === 'movie' ? item.release_date : item.first_air_date;
    
    // 获取海报URL - 使用完整的poster_url属性，而不是poster_path
    const posterPath = item.poster_url ? item.poster_url : '/static/images/placeholder.png';
    
    // 构建卡片HTML
    card.innerHTML = `
        <div class="tmdb-poster-container">
            <img src="${posterPath}" alt="${title}" class="tmdb-poster">
        </div>
        <div class="tmdb-title">${title}</div>
        <div class="tmdb-release-date">${releaseDate ? formatDate(releaseDate) : '未知日期'}</div>
    `;
    
    // 添加点击事件
    card.addEventListener('click', function() {
        openMediaDetailModal(item.id, type);
    });
    
    return card;
}

// 格式化日期
function formatDate(dateString) {
    if (!dateString) return '';
    
    const date = new Date(dateString);
    return date.toLocaleDateString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit'
    });
}

// 添加到收藏夹功能（预留）
function addToFavorites(id, type) {
    // 这里可以实现添加到收藏夹的逻辑
    console.log(`添加${type} ${id}到收藏夹`);
}

// 下载海报功能
function downloadPoster() {
    const mediaData = JSON.parse(this.dataset.media);
    const posterUrl = mediaData.poster_url;
    const title = mediaData.type === 'movie' ? mediaData.title : mediaData.name;
    
    if (!posterUrl) {
        alert('暂无海报可下载');
        return;
    }
    
    // 创建一个临时链接进行下载
    const link = document.createElement('a');
    link.href = `/api/tmdb/download-poster?url=${encodeURIComponent(posterUrl)}&title=${encodeURIComponent(title)}`;
    link.download = `${title}_poster.jpg`;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    
    window.showNotification('海报下载开始', 'success');
}

// 生成NFO文件功能
function generateNFOFile() {
    const mediaData = JSON.parse(this.dataset.media);
    const mediaId = mediaData.id;
    const mediaType = mediaData.type;
    const title = mediaData.type === 'movie' ? mediaData.title : mediaData.name;
    
    // 显示加载状态
    this.disabled = true;
    this.innerHTML = '<i class="fa fa-spinner fa-spin mr-2"></i> 生成中...';
    
    // 发送请求生成NFO文件
    fetch(`/api/tmdb/generate-nfo?id=${mediaId}&type=${mediaType}`)
        .then(response => response.json())
        .then(data => {
            this.disabled = false;
            this.innerHTML = '<i class="fa fa-file-code-o mr-2"></i> 生成NFO文件';
            
            if (data.success && data.data && data.data.nfo_path) {
                // 显示生成成功信息
                const nfoResult = document.getElementById('nfo-result');
                const nfoFilePath = document.getElementById('nfo-file-path');
                
                nfoFilePath.textContent = `文件路径: ${data.data.nfo_path}`;
                nfoResult.classList.remove('hidden');
                
                window.showNotification('NFO文件生成成功', 'success');
            } else {
                window.showNotification(data.message || 'NFO文件生成失败', 'error');
            }
        })
        .catch(error => {
            console.error('生成NFO文件失败:', error);
            this.disabled = false;
            this.innerHTML = '<i class="fa fa-file-code-o mr-2"></i> 生成NFO文件';
            window.showNotification('NFO文件生成失败', 'error');
        });
}

// 绑定关闭弹窗事件
function setupModalEvents() {
    const modal = document.getElementById('media-detail-modal');
    const closeModalBtn = document.getElementById('close-modal');
    
    // 点击关闭按钮关闭弹窗
    if (closeModalBtn) {
        closeModalBtn.addEventListener('click', function() {
            modal.classList.add('hidden');
        });
    }
    
    // 点击弹窗外部关闭弹窗
    modal.addEventListener('click', function(e) {
        if (e.target === modal) {
            modal.classList.add('hidden');
        }
    });
    
    // 按ESC键关闭弹窗
    document.addEventListener('keydown', function(e) {
        if (e.key === 'Escape' && !modal.classList.contains('hidden')) {
            modal.classList.add('hidden');
        }
    });
}

// 修改页面初始化函数，添加弹窗事件绑定
function initPage() {
    // 绑定搜索按钮事件
    document.getElementById('search-button').addEventListener('click', performSearch);
    document.getElementById('tmdb-search-input').addEventListener('keypress', function(e) {
        if (e.key === 'Enter') {
            performSearch();
        }
    });
    
    // 绑定刷新按钮事件
    document.getElementById('refresh-movies').addEventListener('click', loadRecentMovies);
    document.getElementById('refresh-tv').addEventListener('click', loadRecentTV);
    
    // 绑定滚动按钮事件
    setupScrollButtons('movies');
    setupScrollButtons('tv');
    
    // 绑定弹窗事件
    setupModalEvents();
    
    // 加载初始数据
    loadRecentMovies();
    loadRecentTV();
}